接下來我都會用 Docker 來實作,流程如下:
FROM python:3.9.5-slim-buster
RUN apt-get update \
&& apt-get -y install libpq-dev gcc vim poppler-utils
# set work directory
WORKDIR /usr/src/app
COPY ./requirements.txt /code/requirements.txt
RUN pip install -U pip
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY . .
def get_application():
app = FastAPI()
app.openapi = custom_openapi
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(docs.router)
app.include_router(test.router, tags=["測試"], prefix="/hello")
app.mount("/static", StaticFiles(directory="static"), name="static")
return app
app = get_application()
from fastapi import APIRouter
router = APIRouter()
@router.get("", summary="Hello World!")
async def hello_world():
"""Hello World"""
return "Hello World"
version: '3'
services:
fastapi:
container_name: fastapi
build: "."
volumes:
- .:/usr/src/app
ports:
- "5000:5000"
command: uvicorn app.main:app --host 0.0.0.0 --port 5000 --reload
docker-compose up -d
位置是 http://localhost:5000/docs
詳細程式碼參考連結